package com.zzj.security.jwt.controller;

import com.zzj.security.jwt.entity.dto.HttpResult;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName HelloController
 * @Description TODO
 * @Author zhijun zeng at 0:17 2020/5/18
 * @Version 1.0
 **/
@RestController
public class HelloController {


    @RequestMapping("/hello")
    public HttpResult helloWorld1() {
        return HttpResult.success();
    }

    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/hello2/{hehe}")
    public HttpResult helloWorld2(@PathVariable(name = "hehe") String hehe) {
        return HttpResult.success(hehe).add("拥有 ADMIN 可以访问");
    }

    /**
     * @Secured 必须 要以 ROLE_ 开头  ROLE_角色名
     *
     * @return
     */
    @Secured({"ROLE_admin","ROLE_dbadmin"})
    @RequestMapping("/hello3")
    public HttpResult helloWorld3() {
        return HttpResult.success().add("descr","拥有 ADMIN 或者 DBADMIN 可以访问");
    }

    /**
     * 用户必须同时拥有normal和admin 方可访问
     * @return
     */
    @RequestMapping("/hello4")
    @PreAuthorize("hasRole('sysadmin') AND hasRole('admin')")
    public HttpResult helloWorld4() {
        return HttpResult.success();
    }

    /**
     * @PostAuthorize 注解使用并不多，在方法执行后再进行权限验证，适合验证带有返回值的权限，
     * Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject
     *
     * @return
     */
    @RequestMapping("/hello5")
    @PostAuthorize(" returnObject!=null &&  returnObject.username == authentication.name")
    public HttpResult helloWorld5() {
        return HttpResult.success();
    }
}
